package com.baigt.jvm.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * 类功能描述:
 *
 * @author baigt
 * @version V1.0
 * @since 2019-06-15 12:22
 */
public class RickyClassCloader extends ClassLoader {

    /**
     * 类加载器名称
     */
    private String loaderName;
    /**
     * 加载类的扩展名
     */
    private String fileExtension=".class";
    /**
     * 加载类的目录
     */
    private String path;

    public RickyClassCloader(ClassLoader parent, String loaderName) {
        super(parent);
        this.loaderName = loaderName;
    }

    public RickyClassCloader(String loaderName) {
        super();
        this.loaderName = loaderName;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("find class from RickyClassLoader");
        byte[] data = this.loadClassData(name);
        return this.defineClass(name, data, 0, data.length);
    }

    private byte[] loadClassData(String name) {
        InputStream is = null;
        byte[] bytes = null;
        ByteArrayOutputStream bos = null;
        name = name.replace(".", File.separator);

        try {
            is = new FileInputStream(new File(path+File.separator+name+fileExtension));
            bos = new ByteArrayOutputStream();
            int ch;
            while (-1 != (ch = is.read())) {
                bos.write(ch);
            }
            bytes = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bytes;
    }

    public void setPath(String path) {
        this.path = path;
    }
}
